package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.exception.BaseException;
import com.ruoyi.system.domain.LanguageType;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.domain.SysDictLanguage;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysDictLanguageMapper;
import com.ruoyi.system.service.ILanguageTypeService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictLanguageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author qy
 * @date 2023/3/17 15:33
 */
@Service
public class SysDictLanguageServiceImpl implements ISysDictLanguageService {

    @Autowired
    private SysDictLanguageMapper sysDictLanguageMapper;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private LanguageTypeServiceImpl languageTypeService;

    @Value("${ruoyi.manage.devModel:false}")
    private Boolean authority;

    @Override
    public List<SysDictLanguage> getByDictCode(Long dictCode) {
        return sysDictLanguageMapper.getByDictCode(dictCode);
    }

    @Override
    public int save(SysDictLanguage sysDictLanguage) {
        if (!authority) {
            throw new BaseException("该环境禁止新增字典");
        }
        return sysDictLanguageMapper.save(sysDictLanguage);
    }

    @Override
    public int update(SysDictLanguage sysDictLanguage) {
        return sysDictLanguageMapper.updateByDictCode(sysDictLanguage);
    }

    @Override
    public int delete(Long dictCode, String type) {
        return sysDictLanguageMapper.delete(dictCode, type);
    }

    @Override
    public Map<String, String> getByDict(String dictType, String code, String applicationCode) {
        Locale locale = LocaleContextHolder.getLocale();
        LanguageType languageByCode = languageTypeService.getLanguageByCode(locale.getLanguage(), applicationCode);
        List<SysDictData> sysDictData = sysDictDataService.selectDictDataByType(dictType, languageByCode.getCode());
        if (sysDictData.size() == 0){
            return new HashMap<>();
        }
        if (code == null) {
            return sysDictData.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        } else {
            return sysDictData.stream().filter(e -> e.getDictValue().equals(code)).collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        }
    }
}
